package server;

import java.util.Vector;

/**
 * This class contains the list of all <br>
 * connected clients and their IDs
 * 
 * @author Michele Massaro 1057513
 *
 */
public class UserList {
	
	static Vector<Integer> list;
	
	public UserList () {
		this.list = new Vector<Integer>(10,10);
		list.add(new Integer(0));
	}
	
	/**
	 * Register a new user
	 * @return user id
	 */
	public int getNewID () {
		
		// possible data race
		synchronized(this) {
			
			boolean freeSpot = false;
			int i; 
			for(i=0; i<list.size() && !freeSpot; i++) {
				if(!((new Integer(1)).equals(list.get(i)))) {
					freeSpot = true;
				}
			}
			if(freeSpot) {
				list.setElementAt(new Integer(1), i-1);
				return i-1;
			} else {
				list.add(new Integer(1));
				return i;
			}
		}
	}
	
	/**
	 * Remove a user from the list when disconnected
	 * @param id of the user
	 * @return false if something gone wrong
	 */
	public boolean removeUser (int id) {
		synchronized (this) {
			if ((new Integer(1)).equals(list.get(id))) {
				list.set(id, new Integer(0));
				return true;
			}
		}
		return false; // debug utility
	}
}
